package com.xhl.demo.async;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @author 徐宏亮
 * @description 监听器
 * ContextRefreshedEvent 系统初始化完毕的事件，我们监听这个，我要做一个事
 * @date 2019/1/16 14:20
 */
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //需要多线程处理，不然会阻塞
        new Thread(() -> {
            while (true) {
                //模拟对象是否有值
                if (StrUtil.isNotBlank(mockQueue.getCompleteOrder())) {
                    //有值时，返回订单处理结果，处理成功后的信息，在放到 deferredResultHolder 里面
                    String orderNumber = mockQueue.getCompleteOrder();
                    logger.info("返回订单处理结果：" + orderNumber);
                    deferredResultHolder.getMap().get(orderNumber).setResult("place order success");
                    //处理后，消息清空
                    mockQueue.setComplateOrder(null);
                } else {
                    //没值，停100毫秒，然后一直循环
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
